<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
    <a-spin :spinning="tagloading">
      <div v-if="openStatus==1 && !form.appid">
        <div class="top-tips">
          <a-alert type="info" style="width: 100%;border:none;">
            <div slot="message" class="desc">
              <span>为保证系统所有功能正常使用，我们仅支持认证服务号接入系统，不支持其他类型公众号。</span>
              <a @click="goWechat">没有认证服务号？去注册</a>
            </div>
          </a-alert>
        </div>
        <div class="bm-btn">
          <a-button type="primary" @click="getUrl"> 我有认证服务号，立即接入 </a-button>
        </div>
      </div>
      <div class="displayFlex" v-else>
        <div style="width: 600px">
          <a-form-model ref="ruleForm" :model="form" :rules="rules" v-bind="layout">
            <a-form-model-item label="公众号名称" prop="name">
              <a-input v-model="form.name" placeholder="请输入公众号名称" :disabled="(openStatus == 1 && inType == 1) || useMain == 1"></a-input>
            </a-form-model-item>
            <a-form-model-item label="AppID" prop="appid">
              <a-input v-model="form.appid" placeholder="请输入AppID" :disabled="(openStatus == 1 && inType == 1) || useMain == 1"></a-input>
            </a-form-model-item>
            <a-form-model-item label="AppSecret" prop="appsecret" v-if="(inType != 1 || openStatus == 0) && useMain == 0">
              <a-input v-model="form.appsecret" placeholder="请输入AppSecret"></a-input>
            </a-form-model-item>
            <a-form-model-item label="公众号二维码" prop="qrcode" v-if="(openStatus == 1 && inType == 1) || useMain == 1">
              <div class="img-box">
                <div class="bg-color"></div>
                <a-icon type="zoom-in" class="font-weizhi" @click="previewVisible = true" />
                <img :src="previewImage" style="width: 100%; height: 100%" />
              </div>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-model-item>
            <a-form-model-item label="公众号二维码" prop="qrcode" v-else>
              <a-upload
                list-type="picture-card"
                :file-list="fileList"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <div v-if="fileList.length < 1">
                  <a-icon type="plus" />
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-model-item>

            <a-form-model-item label=" " :colon="false" v-if="useMain == 0">
              <a-button @click="getUrl" type="primary" v-if="openStatus == 1 && inType == 1">重新授权</a-button>
              <a-button @click="setIndustry" type="primary" v-if="openStatus == 1 && inType == 1">设置模板消息行业</a-button>
              <a-button @click="submit('ruleForm')" type="primary" style="margin-right: 15px" v-if="inType != 1 || (openStatus == 0 && inType == 1)">保存</a-button>
              <a-button @click="getUrl" type="default" v-if="openStatus == 1 && inType != 1">更换为授权接入</a-button>
            </a-form-model-item>
            <a-form-model-item label="微信绑定物料" :colon="false">
              <a-button @click="showModalOfDownload">去下载</a-button>
            </a-form-model-item>
            <a-form-model-item label="公众号授权文件" :colon="false" v-if="inType != 1 && useMain == 0">
              <a-upload :before-upload="beforeUploadTxt" :showUploadList="false" accept=".txt">
                <a-button> <a-icon type="upload" />去上传 </a-button>
              </a-upload>
            </a-form-model-item>
          </a-form-model>
        </div>
        <div class="entry">
          <a-form-model v-bind="{ labelCol: { span: 4 }, wrapperCol: { span: 20 } }">
            <a-form-model-item label="教师端入口">
              <a
                class="btn_url_1"
                :data-clipboard-text="hostUrl + '/h5/#/pagesTeacher/index/index?sid=' + $store.state.user.school"
                @click="copyUrl1"
              >{{ hostUrl }}/h5/#/pagesTeacher/index/index?sid={{ $store.state.user.school }}</a
              >
              <a-popover placement="right">
                <template slot="content" style="padding: 0 !important">
                  <div style="padding: 12px 16px">
                    <vue-qr
                      :text="hostUrl + '/h5/#/pagesTeacher/index/index?sid=' + $store.state.user.school"
                      :size="100"
                      :margin="0"
                    ></vue-qr>
                  </div>
                </template>
                <a-icon type="qrcode" class="qrCodeICon" />
              </a-popover>
            </a-form-model-item>
            <a-form-model-item label="家长端入口">
              <a
                class="btn_url_2"
                :data-clipboard-text="hostUrl + '/h5/#/pages/index/index?sid=' + $store.state.user.school"
                @click="copyUrl2"
              >{{ hostUrl }}/h5/#/pages/index/index?sid={{ $store.state.user.school }}</a
              >
              <a-popover placement="right">
                <template slot="content" style="padding: 0 !important">
                  <div style="padding: 12px 16px">
                    <vue-qr
                      :text="hostUrl + '/h5/#/pages/index/index?sid=' + $store.state.user.school"
                      :size="100"
                      :margin="0"
                    ></vue-qr>
                  </div>
                </template>
                <a-icon type="qrcode" class="qrCodeICon" />
              </a-popover>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </a-spin>
    <a-modal
      title="家校推广物料"
      :visible="downloadVisible"
      :footer="null"
      @cancel="downloadVisible = false"
      :bodyStyle="{ height: '500px', 'overflow-y': 'auto' }"
    >
      <div class="wallpapers">
        <div class="left">
          <div style="margin-bottom: 8px; font-size: 16px; color: #333">海报</div>
          <div class="img">
            <img :src="posterurl" alt />
          </div>
        </div>
        <div class="right">
          <div style="margin-bottom: 8px; font-size: 16px; color: #333">易拉宝</div>
          <div class="img">
            <img :src="posterurl1" alt />
          </div>
        </div>
      </div>
      <div class="downLoadBtn">
        <a-button size="small" @click="downPhoto(zip)">下载</a-button>
      </div>
      <div class="textArea">
        <div class="title">朋友圈宣传参考文案</div>
        <div class="text-box">
          <pre class="text">
          【重要通知】亲爱的家长：
          在教育的路上，我校一直秉承着专心教学，用心服务的宗旨。
          为方便家长们实时了解孩子上课情况，提升我校教学服务能力，我校特引进“{{ text_company_name }}”家校服务系统。
          扫描下图二维码绑定学员账号，即可实时掌握孩子课堂情况，享受我校优质的家校服务！
        </pre
          >
          <a-button class="btn_1" :data-clipboard-text="content1" size="small" @click="copy1">复制</a-button>
        </div>
        <div class="text-box">
          <pre class="text">
          各位家长，注意啦～
          为提高本校信息化服务能力，拉近与家长孩子们的距离，我校特引进“{{ text_company_name }}”家校服务系统。
          现在扫一扫下图二维码，即可享受我校信息化家校服务。
          不错过孩子每一个成长瞬间。
        </pre
          >
          <a-button class="btn_2" size="small" :data-clipboard-text="content2" @click="copy2">复制</a-button>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import QRCode from 'qrcodejs2'
import { uploadPic, companyInfo } from '@/api/login'
import { getSchoolWX, setSchoolWX, dowmLoadThing, uploadTxt, getAuthorized,setIndustry } from '@/api/organization'
import vueQr from 'vue-qr'
import Clipboard from 'clipboard'

export default {
  components: {
    vueQr
  },
  data () {
    return {
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 }
      },
      loading: false, // 上传图片的loading
      tagloading: false,
      form: {
        name: '',
        appid: null,
        appsecret: null,
        qrcode: null
      },
      fileList: [],
      previewVisible: false,
      previewImage: '',
      rules: {
        name: [{ required: true, message: '请输入公众号名称', trigger: 'blur' }],
        appid: [{ required: true, message: '请输入AppID', trigger: 'blur' }],
        appsecret: [{ required: true, message: '请输入AppSecret', trigger: 'blur' }],
        qrcode: [{ required: true, message: '请上传公众号二维码', trigger: 'blur' }]
      },
      downloadVisible: false,
      text_company_name: '',
      content1: '',
      content2: '',
      posterurl: '',
      posterurl1: '',
      zip: '',
      hostUrl: null,
      openStatus: 0,
      inType: 0,
      useMain: 0
    }
  },
  created () {
    if (this.$route.query.msg == 1) {
      this.$error({
        title: '公众号授权接入失败',
        content: '公众号已接入其他学校，请在其他学校取消接入以后，再接入本学校'
      })
    }
    const ishttps = document.location.protocol == 'https:'
    if (ishttps) {
      this.hostUrl = 'https://' + window.location.host
    } else {
      this.hostUrl = 'http://' + window.location.host
    }
    companyInfo().then((res) => {
      this.text_company_name = res.value.name
      this.content1 =
        `【重要通知】亲爱的家长：
          在教育的路上，我校一直秉承着专心教学，用心服务的宗旨。
          为方便家长们实时了解孩子上课情况，提升我校教学服务能力，我校特引进“` +
        res.value.name +
        `”家校服务系统。
          扫描下图二维码绑定学员账号，即可实时掌握孩子课堂情况，享受我校优质的家校服务！`
      this.content2 =
        `各位家长，注意啦～
          为提高本校信息化服务能力，拉近与家长孩子们的距离，我校特引进“` +
        res.value.name +
        `”家校服务系统。
          现在扫一扫下图二维码，即可享受我校信息化家校服务。
          不错过孩子每一个成长瞬间。`
    })
    this.getData()
  },
  methods: {
    setIndustry(){
      setIndustry({ school_id: this.$store.state.user.school })
        .then((res) => {
          this.$message.success('设置成功')
        })
        .catch((err) => {
          this.$message.error(err.data.message || '设置失败')
        })
    },
    getUrl () {
      getAuthorized({ school_id: this.$store.state.user.school })
        .then((res) => {
          window.open(res, '_blank')
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取地址失败')
        })
    },
    goWechat () {
      window.open('https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN&token=', '_blank')
    },
    showModalOfDownload () {
      this.tagloading = true
      dowmLoadThing(this.$store.state.user.school, { school_id: this.$store.state.user.school, key: 'official_account' })
        .then((res) => {
          this.posterurl = res.poster + '?temp=' + Math.random()
          this.posterurl1 = res.process + '?temp=' + Math.random()
          this.zip = res.zip_file
          this.downloadVisible = true
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取下载资源失败')
        })
        .finally(() => {
          this.tagloading = false
        })
    },
    getData () {
      this.tagloading = true
      getSchoolWX({
        school_id: this.$store.state.user.school,
        key: 'official_account'
      })
        .then((res) => {
          if (res.value && !(res.value instanceof Array)) {
            this.form = res.value
            this.openStatus = res.value.openStatus
            this.inType = Number(res.value.type)
            this.useMain = Number(res.value.useMain)
            if (res.value.qrcode.url) {
              this.previewImage = res.value.qrcode.url + '?temp=' + Math.random()
              this.fileList = [
                {
                  name: res.value.qrcode.path,
                  uid: '-1',
                  url: res.value.qrcode.url
                }
              ]
            }
          }
        })
        .catch((err) => {
          this.$message.error(err.data.message || '加载数据失败~')
        })
        .finally(() => {
          this.tagloading = false
        })
    },
    beforeUpload (file) {
      this.fileList = []
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png图片格式！')
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('只能上传10MB以内的图片!')
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('school_id', this.$store.state.user.school)
      this.loading = true
      uploadPic(formData)
        .then((res) => {
          this.previewImage = res.url
          this.fileList = [
            {
              name: res.path,
              uid: '-1',
              url: res.url
            }
          ]
          this.form.qrcode = res
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
          this.$message.error(err.data.message || '上传失败，请稍后重试~')
        })
      return false
    },
    handleCancel () {
      this.previewVisible = false
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.tagloading = true
          const params = JSON.parse(JSON.stringify(this.form))
          if (params.qrcode == '') {
            this.$message.error('请上传公众号二维码')
          } else {
            setSchoolWX({
              school_id: this.$store.state.user.school,
              key: 'official_account',
              value: params
            })
              .then((res) => {
                this.$message.success('设置成功')
                this.getData()
              })
              .catch((err) => {
                this.tagloading = false
                this.$message.error(err.data.message || '设置失败')
              })
          }
        } else {
          return false
        }
      })
    },
    copy1 () {
      const clipboard = new Clipboard('.btn_1')
      clipboard.on('success', (e) => {
        this.$message.success('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$message.error('该浏览器不支持自动复制')
        clipboard.destroy()
      })
    },
    copy2 () {
      const clipboard = new Clipboard('.btn_2')
      clipboard.on('success', (e) => {
        this.$message.success('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$message.error('该浏览器不支持自动复制')
        clipboard.destroy()
      })
    },
    copyUrl1 () {
      const clipboard = new Clipboard('.btn_url_1')
      clipboard.on('success', (e) => {
        this.$message.success('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$message.error('该浏览器不支持自动复制')
        clipboard.destroy()
      })
    },
    copyUrl2 () {
      const clipboard = new Clipboard('.btn_url_2')
      clipboard.on('success', (e) => {
        this.$message.success('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$message.error('该浏览器不支持自动复制')
        clipboard.destroy()
      })
    },
    // 下载图片
    downPhoto (blobUrl) {
      window.open(blobUrl, '_blank')
    },
    beforeUploadTxt (data) {
      this.loading = true
      const _this = this
      const formData = new FormData()
      formData.append('file', data)
      formData.append('school_id', this.$store.state.user.school)
      uploadTxt(formData)
        .then((res) => {
          _this.$message.success('上传成功')
          _this.loading = false
        })
        .catch((err) => {
          _this.loading = false
          _this.$message.error(err.data.message || '上传失败，请稍后重试~')
        })
      return false
    }
  },
  watch: {
    downloadVisible (val) {
      if (val == false) {
        this.zip = ''
        this.posterurl = ''
        this.posterurl1 = ''
      }
    }
  }
}
</script>
<style lang="less">
.ant-popover-inner-content {
  padding: 0 !important;
}
</style>
<style lang="less" scoped>
.btn_url_1,
.btn_url_2 {
  display: inline-block;
  line-height: 20px;
}
.displayFlex {
  display: flex;
  .entry {
    width: 800px;
  }
}
.wallpapers {
  display: flex;
  text-align: center;
  justify-content: center;
  .left,
  .right {
    height: 300px;
    .img {
      height: 271px;
      overflow: hidden;
      img {
        height: 100%;
        width: auto;
      }
    }
  }
  .left {
    margin-right: 20px;
  }
  // .right{
  //     height:271px;
  //     overflow: hidden;
  // }
}
.textArea {
  .title {
    margin-bottom: 8px;
    color: #333;
    font-size: 16px;
    font-weight: 500;
  }
  .text-box {
    margin-bottom: 16px;
    padding: 8px 12px;
    padding-bottom: 20px;
    border: 1px solid #e8e8e8;
    border-radius: 3px;
    text-align: left;
    position: relative;
    pre.text {
      margin-top: 0;
      margin-bottom: 20px;
      font-size: 14px;
      overflow: auto;
      white-space: pre-line;
      line-height: 24px;
    }
    .btn_1,
    .btn_2 {
      position: absolute;
      right: 12px;
      bottom: 10px;
    }
  }
}
.downLoadBtn {
  margin: 20px 0;
  text-align: center;
}
.qrCodeICon {
  position: relative;
  font-size: 20px;
  margin-left: 20px;
  top: 2px;
  cursor: pointer;
}
.top-tips {
  // height: 30px;
  // background: #d7d7d7;
  color: #333;
  width: 60%;
}
.desc {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bm-btn {
  margin-top: 50px;
}
.img-box {
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid #d9d9d9;
  position: relative;
}
.img-box:hover .bg-color {
  display: block;
}
.img-box:hover .font-weizhi {
  display: block;
}
.bg-color {
  display: none;
  background: rgba(0, 0, 0, 0.5);
  z-index: 11;
  width: 88px;
  height: 88px;
  position: absolute;
}
.font-weizhi {
  display: none;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 20px;
  z-index: 22;
  cursor: pointer;
}
</style>
